package com.roger.uia;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.util.Log;

import com.roger.uia.helper.UiBase;
import com.roger.uia.helper.UiCom;
import com.roger.uia.helper.UiWatch;
import com.roger.uia.helper.manager.Package;
import com.roger.uia.helper.util.FileUtils;
import com.roger.uia.helper.util.StrUtils;
import com.roger.uia.helper.util.ZipUtils;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.roger.uia.helper.UiBase.filePath;
import static com.roger.uia.helper.UiBase.getObj;
import static com.roger.uia.helper.UiBase.mDevice;
import static com.roger.uia.helper.UiBase.objSelect;
import static com.roger.uia.helper.UiBase.waitTime;

@SuppressWarnings("ConstantConditions")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestWifiUserForP11 {
    private static final String TAG = TestWifiUserForP11.class.getSimpleName();
    private WifiManager wifiManager = (WifiManager) InstrumentationRegistry.getTargetContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    private ConnectivityManager connManager = (ConnectivityManager) InstrumentationRegistry.getTargetContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    private String[] wifiList;
    private Date timeMUnConn; //断开重连时间点
    private String baiDuP,routerP;
    private Boolean isMonitor=true;//监控线程是否继续
    private int unConnTimes = 0;//断连总次数
    private int connFlag = 0;//连接标志，是否为断开重连
    private int unConnFlag = 0;//断开标志，是否不为刚断开
    private int errorFlag = 0;//本轮测试异常标志
    private String tencent,douyin,douyu,weibo,internet,download,apk_address;
    private int tencent_play_time,douyin_play_time,douyu_play_time,weibo_play_time,internet_search_time,refresh_gap;
    private static ArrayList<cases> testCase = new ArrayList<>();//测试列表

    @BeforeClass
    public static void beforeClass() throws Throwable {
        if(!mDevice.isScreenOn()) mDevice.wakeUp();
        mDevice.pressHome();
    }

    @Before
    public void setUp()  {
        Log.d(TAG,"-- set up --");
        Package.pac().grantAllPerms(InstrumentationRegistry.getTargetContext().getPackageName());
        UiCom.setScreenOn();
        UiWatch.getWatcher().runErrorWatcher();
        UiWatch.getWatcher().runSpecialWatcher();
        UiMonitor();
    }

    @After
    public void tearDown() {
        Log.d(TAG,"-- tear down --");
        UiWatch.getWatcher().removeErrorWatcher();
        UiWatch.getWatcher().removeSpecialWatcher();
    }

    @AfterClass
    public static void afterClass() throws Throwable {
        mDevice.pressHome();
        mDevice.executeShellCommand("am start -a android.intent.action.MAIN -n com.roger.wificfg/com.roger.wificfg.MainActivity --ei pid 0");
        UiBase.waitObjCheck(UiBase.objSelect[0],"CONNECT REPORT",10);
        mDevice.executeShellCommand("am broadcast -a com.roger.wificfg.OPEN_URL --es url end");
    }

    @Test
    public void UserTest_checkWifi(){
        String logPath = filePath +"log";;
        String casesRandom = getOtherCfg(filePath+"testWifi/config/other.cfg","casesRandom:");
        int testTimes =Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","times:"));
        getWifiCfg(filePath+"testWifi/config/wifi.cfg");
        getOtherCfg();
        addTestCase();
        List list = Arrays.asList(wifiList);
        for (int t=0;t<testTimes;t++){
            Collections.shuffle(list);
            for(int i=0;i<list.size();i++){
                String[] wifiInfo =  ((String) list.get(i)).split("<->");
                String isSearchable = wifiInfo[0];
                String wifiName = wifiInfo[1];
                String wifiPwd = wifiInfo[2];
                String security = wifiInfo[3];
                String routerIP = wifiInfo[4];
                String reportName = wifiName.replaceAll(" ","");
                if(!FileUtils.existFile(filePath+"testWifi/result/"+reportName+".csv")){
                    FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv","DateTime,ConnState,UpRates,DownRates,RSSI,PingBaiDu,PingRouter,UnConnTimes,UnConnAllTime(s),");
                }
                UiObject menuText = mDevice.findObject(new UiSelector().textMatches(wifiName));
                UiObject menuTextAdd = mDevice.findObject(new UiSelector().textMatches("(?i)Add network|添加网络"));
                UiScrollable secMenuList= new UiScrollable(new UiSelector().resourceId(StrUtils.recycler));
                try {
                    removeWifiSaved();
                    Log.d(TAG, "connect wifi :" + wifiName);
                    enterWLAN();
                    switch (isSearchable) {
                        case "true":
                            for (int j = 0; j < 3; j++) {
                                secMenuList.scrollIntoView(menuText);
                                if (menuText.exists()) {
                                    menuText.clickAndWaitForNewWindow();
                                    break;
                                }
                            }
                            if (!wifiPwd.equals("null")) {
                                UiBase.waitObjCheck(UiBase.objSelect[3], StrUtils.password, 5);
                                UiBase.inputTxtToObj(UiBase.objSelect[3], StrUtils.password, wifiPwd);
                                UiBase.waitClickObj(UiBase.objSelect[2], StrUtils.connect, 10);
                            }
                            checkConnect();
                            break;
                        case "false":
                            for (int j = 0; j < 3 ;j++){
                                secMenuList.scrollIntoView(menuTextAdd);
                                if(menuTextAdd.exists()) {
                                    menuTextAdd.clickAndWaitForNewWindow();
                                    break;
                                }
                            }
                            UiBase.waitObj(UiBase.objSelect[3],"com.android.settings:id/ssid",3);
                            UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/ssid",wifiName);
                            if(!wifiPwd.equals("null")){
                                UiBase.clickObj(UiBase.objSelect[3],"com.android.settings:id/security");
                                UiBase.waitClickObj(UiBase.objSelect[0],security,5);
                                UiBase.waitObj(UiBase.objSelect[3],"com.android.settings:id/password",3);
                                UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/password",wifiPwd);
                            }
                            UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[3],"com.android.settings:id/wifi_advanced_togglebox");
                            UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[3],"com.android.settings:id/hidden_settings");
                            UiBase.waitClickObj(UiBase.objSelect[2],"Yes|是",3);
                            UiBase.waitClickObj(UiBase.objSelect[2],"SAVE|保存",3);
                            checkConnect();
                            break;
                        default:
                            for (int j = 0; j < 3; j++) {
                                secMenuList.scrollIntoView(menuText);
                                if (menuText.exists()) {
                                    menuText.clickAndWaitForNewWindow();
                                    break;
                                }
                            }
                            UiBase.waitClickObj(UiBase.objSelect[3],"com.android.settings:id/ca_cert",3);
                            UiBase.waitClickObj(UiBase.objSelect[2],"(?i)allow|不验证|Do not validate",3);
                            UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[3],StrUtils.identity);
                            UiBase.inputTxtToObj(UiBase.objSelect[3],StrUtils.identity,wifiPwd);
                            UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[3],StrUtils.password);
                            UiBase.inputTxtToObj(UiBase.objSelect[3],StrUtils.password,security);
                            UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.connect,3);
                            checkConnect();
                            break;
                    }
                    changePrivacy(wifiName);
                    //start test
                    try{
                        logOn(true);
                        String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
                        FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",timeMS+",connect success");
                        if(casesRandom.equals("true")) Collections.shuffle(testCase);
                        connFlag=0;
                        wifiMonitor(reportName,wifiName,routerIP);
                        for(int m=0;m<testCase.size();m++){
                            testCase.get(m).run(wifiName);
                            if(errorFlag==1){
                                Log.d(TAG,"disconnect has happened,skip next tests");
                                break;
                            }
                        }
                    }catch (Throwable e){
                        Log.d(TAG,"error with test");
                    }finally {
                        isMonitor=false;
                        logOn(false);
                        if(FileUtils.existFile(logPath)) {
                            try{
                                if(errorFlag==1) {
                                    Log.d(TAG,"disconnect happen,start zip logs");
                                    String logTime = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
                                    ZipUtils.zip().zipFile(logPath, filePath+"logs_"+ logTime + ".zip");
                                    Log.d(TAG,"zip logs end");
                                } else Log.d(TAG,"no disconnect happen,start clear logs");
                                mDevice.executeShellCommand("rm -rf "+ logPath);
                            }catch (Throwable e){
                                Log.d(TAG,"copy logs fail");
                                e.printStackTrace();
                            }
                        }
                        mDevice.pressHome();
                        errorFlag=0;
                    }
                }catch (Throwable e){
                    String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
                    FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",timeMS+",connect fail");
                    Log.d(TAG,"connect wifi fail");
                    e.printStackTrace();
                }
            }
        }
    }



    private void logOn(boolean b){
        if (!UiBase.existObj(UiBase.objSelect[2], "LenovoLogger")){
            try{
                UiBase.startApp("com.lenovo.loggerpannel/.PannelActivity");
                UiBase.waitObj(UiBase.objSelect[2],"Warnning",10);
                if(UiBase.existObj(UiBase.objSelect[2],"Warnning")) mDevice.pressBack();
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
        try{
            if(b){
                if(UiBase.objEnabled(UiBase.objSelect[2],"Main log"))
                    UiBase.waitClickObj(UiBase.objSelect[3],"com.lenovo.loggerpannel:id/start",3);
            }else{
                if(!UiBase.objEnabled(UiBase.objSelect[2],"Main log")){
                    UiBase.waitClickObj(UiBase.objSelect[3],"com.lenovo.loggerpannel:id/start",3);
                    UiBase.waitObjGone(UiBase.objSelect[2],"Stop recording and save|停止记录并保存",600);
                }
            }
            SystemClock.sleep(waitTime * 5);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    private void enterWLAN() throws Throwable {
        if (UiBase.existObj(UiBase.objSelect[2],StrUtils.wifi) && UiBase.existObj(UiBase.objSelect[3],StrUtils.frictionIcon)) {
            SystemClock.sleep(waitTime);
        } else {
            mDevice.pressHome();
            UiBase.openApp(StrUtils.settingPac);
            UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingScroll,10);
            UiBase.scrollReidClickObj(StrUtils.settingScroll,UiBase.objSelect[2],StrUtils.settingNetwork);
            UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.wifi,5);
            UiBase.waitObj(UiBase.objSelect[3],StrUtils.switch_widget,5);
            if (UiBase.getTxtFromObj(UiBase.objSelect[3],StrUtils.switch_widget).matches(StrUtils.off)) {
                UiBase.clickObj(UiBase.objSelect[3],StrUtils.switch_widget);
                SystemClock.sleep(waitTime * 10);
            }
            SystemClock.sleep(waitTime);
        }
    }

    private void removeWifiSaved(){
        try{
            enterWLAN();
            UiScrollable secMenuList = new UiScrollable(new UiSelector().resourceId(StrUtils.settingList));
            UiScrollable secMenuListX = new UiScrollable(new UiSelector().resourceId(StrUtils.recycler));
            for(int j=0;j<3;j++){
                if(Build.VERSION.SDK_INT >= 29)
                    secMenuListX.scrollIntoView(UiBase.getObj(UiBase.objSelect[2],StrUtils.savedWifi));
                else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                    secMenuList.scrollIntoView(UiBase.getObj(UiBase.objSelect[2],StrUtils.savedWifi));
                else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    UiBase.clickObj(UiBase.objSelect[6],"(?i)Configure|配置");
                else
                    mDevice.pressMenu();

                if(UiBase.existObj(UiBase.objSelect[2],StrUtils.savedWifi)) {
                    UiBase.clickObj(UiBase.objSelect[2],StrUtils.savedWifi);
                    ArrayList<String> savedWifi = new ArrayList<>();
                    UiObject list = getObj(objSelect[3],"com.android.settings:id/recycler_view");
                    for(int i =0;i <list.getChildCount();i++){
                        UiObject saved = list.getChild(new UiSelector().className("android.widget.TextView").instance(i));
                        Log.d(TAG,saved.getText());
                        savedWifi.add(saved.getText());
                    }
                    for (String wifi : savedWifi) {
                        if (UiBase.existObj(UiBase.objSelect[0],wifi)){
                            UiBase.clickObj(UiBase.objSelect[0],wifi);
                            UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.forget,3);
                        }
                    }
                    break;
                }else {
                    Log.d(TAG,"find saved wifi fail");
                }
            }
        }catch (Throwable e){
            Log.d(TAG,"remove saved wifi fail");
            e.printStackTrace();
        }finally {
            mDevice.pressBack();
        }
    }

    //解析wifi配置文件
    private void getWifiCfg(String path){
        try {
            File file = new File(path);
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                if(!line.startsWith("#")){
                    stringBuilder.append(line);
                    stringBuilder.append("\n");
                }
            }
            wifiList=stringBuilder.toString().split("\n");
            br.close();
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //解析其他配置信息
    private String getOtherCfg(String path,String startTag){
        String s ="";
        try {
            File file = new File(path);
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                if(line.startsWith(startTag)){
                    stringBuilder.append(line);
                }
            }
            s = stringBuilder.toString().replaceAll(startTag,"").replaceAll(" ","");
            br.close();
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return s;
    }

    private void getOtherCfg(){
        tencent = getOtherCfg(filePath+"testWifi/config/other.cfg","tencent:");
        tencent_play_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","tencent_play_time:"));
        douyin = getOtherCfg(filePath+"testWifi/config/other.cfg","douyin:");
        douyin_play_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","douyin_play_time:"));
        douyu = getOtherCfg(filePath+"testWifi/config/other.cfg","douyu:");
        douyu_play_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","douyu_play_time:"));
        weibo = getOtherCfg(filePath+"testWifi/config/other.cfg","weibo:");
        weibo_play_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","weibo_play_time:"));
        internet = getOtherCfg(filePath+"testWifi/config/other.cfg","internet:");
        internet_search_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","internet_search_time:"));
        download = getOtherCfg(filePath+"testWifi/config/other.cfg","download:");
        apk_address = getOtherCfg(filePath+"testWifi/config/other.cfg","apk_address:");
        refresh_gap = Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","refresh_gap:"));
        if (refresh_gap==0) refresh_gap=(int)(5+16*Math.random());
    }

    private void playTencentVideo(int timeTest,String wifiName){
        mDevice.pressHome();
        try {
            String content = getOtherCfg(filePath+"testWifi/config/other.cfg","tencent_content:");
            UiBase.forceStopApp("com.tencent.qqlive");
            UiBase.openApp("com.tencent.qqlive");
            UiBase.waitClickIfObjExist(UiBase.objSelect[2],"同意",5);
            UiBase.waitClickIfObjExist(UiBase.objSelect[2],"我知道了",5);
            UiBase.waitClickObj(UiBase.objSelect[3],"com.tencent.qqlive:id/a8y",3);
            UiBase.waitObj(UiBase.objSelect[3],"com.tencent.qqlive:id/yh",3);
            UiBase.inputTxtToObj(UiBase.objSelect[3],"com.tencent.qqlive:id/yh",content);
            UiBase.waitClickObj(UiBase.objSelect[2],"搜索",3);
            UiBase.waitClickObj(UiBase.objSelect[2],"立即播放",10);
            UiBase.waitObjCheck(UiBase.objSelect[3],"com.tencent.qqlive:id/byn",5);
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play tencent video start");
            Log.d(TAG,"start play tencent video");
            SystemClock.sleep(waitTime * timeTest);
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play tencent video fail");
            Log.d(TAG,"play tencent video fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.tencent.qqlive");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void playDouyin(int timeGap,int timeTest,String wifiName){
        mDevice.pressHome();
        try{
            UiBase.forceStopApp("com.ss.android.ugc.aweme");
            UiBase.openApp("com.ss.android.ugc.aweme");
            UiBase.waitObjCheck(UiBase.objSelect[0],"首页",10);
            int count=0;
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play douyin start");
            Log.d(TAG,"start play douyin video");
            while(count < timeTest/timeGap) {
                SystemClock.sleep(waitTime * timeGap);
                mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H / 2, StrUtils.SCREEN_W / 2, 10, 100);
                count++;
            }
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play douyin fail");
            Log.d(TAG,"play douyin fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.ss.android.ugc.aweme");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void playDouyu(int timeTest,String wifiName){
        mDevice.pressHome();
        try{
            String zhubo = getOtherCfg(filePath+"testWifi/config/other.cfg","douyu_zhubo:");
            String content = getOtherCfg(filePath+"testWifi/config/other.cfg","douyu_content:");
            UiBase.forceStopApp("air.tv.douyu.android");
            UiBase.openApp("air.tv.douyu.android");
            //检测更新
            UiBase.waitClickIfObjExist(UiBase.objSelect[3],"air.tv.douyu.android:id/b2k",10);
            //查询历史记录并播放
            UiBase.waitClickObj(UiBase.objSelect[3],"air.tv.douyu.android:id/cj6",3);
            UiBase.waitClickObj(UiBase.objSelect[3],"air.tv.douyu.android:id/cpc",3);
            UiBase.inputTxtToObj(UiBase.objSelect[3],"air.tv.douyu.android:id/cpc",zhubo);
            mDevice.pressEnter();
            UiBase.waitClickObj(UiBase.objSelect[1],content,10);
            UiBase.waitClickIfObjExist(UiBase.objSelect[3],"air.tv.douyu.android:id/atk",10);
            UiBase.waitObjCheck(UiBase.objSelect[0],"聊天",10);
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play douyu start");
            Log.d(TAG,"start play douyu video");
            SystemClock.sleep(waitTime * timeTest);
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play douyu fail");
            Log.d(TAG,"play douyu fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("air.tv.douyu.android");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void playWeibo(int timeGap,int timeTest,String wifiName){
        mDevice.pressHome();
        try{
            UiBase.forceStopApp("com.sina.weibo");
            UiBase.openApp("com.sina.weibo");
            UiBase.waitClickIfObjExist(UiBase.objSelect[3],"com.sina.weibo:id/tv_title_lookaround",10);
            UiBase.waitClickIfObjExist(UiBase.objSelect[3],"com.sina.weibo:id/tv_title_lookaround",5);
            UiBase.waitClickObj(UiBase.objSelect[6],"Discover|发现",5);
            UiBase.waitObjCheck(UiBase.objSelect[3],"com.sina.weibo:id/tv_search_keyword",3);
            mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H /2, StrUtils.SCREEN_W / 2,10, 100);
            mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H /2, StrUtils.SCREEN_W / 2,10, 100);
            int count=0;
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play weibo start");
            Log.d(TAG,"start play weibo");
            while(count < timeTest/timeGap) {
                SystemClock.sleep(waitTime * timeGap);
                mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H / 2, StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H - 10, 100);
                count++;
            }
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play weibo fail");
            Log.d(TAG,"play weibo fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.sina.weibo");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void searchInternet(int timeGap,int timeTest,String wifiName){
        mDevice.pressHome();
        try {
            String content = getOtherCfg(filePath+"testWifi/config/other.cfg","internet_address:");
            UiBase.forceStopApp("com.roger.wificfg");
            mDevice.executeShellCommand("am start -a android.intent.action.MAIN -n com.roger.wificfg/com.roger.wificfg.MainActivity --ei pid 0");
            UiBase.waitObjCheck(UiBase.objSelect[0],"CONNECT REPORT",10);
            mDevice.executeShellCommand("am broadcast -a com.roger.wificfg.OPEN_URL --es url "+ content);
            UiBase.waitObjCheck(UiBase.objSelect[0],"百度一下,你就知道",10);
            SystemClock.sleep(waitTime*timeGap);
            int count=0;
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",search internet start");
            Log.d(TAG,"start search the internet");
            while(count < timeTest/timeGap) {
                SystemClock.sleep(waitTime * timeGap);
                mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H - 10, StrUtils.SCREEN_W / 2, 10, 100);
                count++;
            }
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",search internet fail");
            Log.d(TAG,"search internet fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.roger.wificfg");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void downloadApk(String apk_address,String wifiName){
        mDevice.pressHome();
        try {
            UiBase.forceStopApp("com.roger.wificfg");
            mDevice.executeShellCommand("am start -a android.intent.action.MAIN -n com.roger.wificfg/com.roger.wificfg.MainActivity --ei pid 1 --es url "+ apk_address);
            UiBase.waitObjCheck(UiBase.objSelect[2],".*%",10);
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",download apk start");
            Log.d(TAG,"start download apk");
            UiBase.waitObjCheck(UiBase.objSelect[0],"download success!",300);
            SystemClock.sleep(waitTime);
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",download apk fail");
            Log.d(TAG,"download apk fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.roger.wificfg");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    @SuppressLint("DefaultLocale")
    private void wifiMonitor0(String reportName, String wifiName, String ip){
        double downloadShow;
        double uploadShow;
        WifiInfo mWifiInfo = wifiManager.getConnectionInfo();
        NetworkInfo mNetInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(mNetInfo.isConnected()){
            if(connFlag==0){
                Log.d(TAG,"conn normal");
                unConnFlag=0;
                int wifiRssi = mWifiInfo.getRssi();
                Date date1= new Date(System.currentTimeMillis());
                long downloadData1 = TrafficStats.getTotalRxBytes();
                long uploadData1 = TrafficStats.getTotalTxBytes();
                SystemClock.sleep(waitTime);
                Date date2= new Date(System.currentTimeMillis());
                long downloadData2 = TrafficStats.getTotalRxBytes();
                long uploadData2 = TrafficStats.getTotalTxBytes();
                downloadShow = (double)(downloadData2 - downloadData1) / 1024 /(double)(date2.getTime()-date1.getTime()) * 1000;
                uploadShow = (double) (uploadData2 - uploadData1) / 1024 / (double)(date2.getTime()-date1.getTime()) * 1000;
                String time = UiBase.dateFormat.format(date2);
                FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",time+",conn,"+String.format("%.2f",uploadShow)+","+
                        String.format("%.2f",downloadShow)+","+String.valueOf(wifiRssi)+", , ,");
            }else{
                Log.d(TAG,"conn again");
                connFlag=0;
                Date timeMConn = new Date(System.currentTimeMillis());
                String time =UiBase.dateFormat.format(timeMConn);
                pingIP(ip);
                FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",time+",conn again, , , ,"+baiDuP+","+routerP+", ,"+String.valueOf((timeMConn.getTime()-timeMUnConn.getTime())/1000));
            }
        }else{
            errorFlag=1;
            Log.d(TAG,"disconnect");
            if(unConnFlag==0){
                unConnTimes++;
                unConnFlag=1;
                FileUtils.takeScreenPicTo(filePath+"testWifi/pic/","disConn_"+wifiName.replaceAll(" ",""));
                timeMUnConn = new Date(System.currentTimeMillis());
                String time  = UiBase.dateFormat.format(timeMUnConn);
                pingIP(ip);
                FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",time+",disConn, , , ,"+baiDuP+","+routerP+","+String.valueOf(unConnTimes)+",");
            }
            connFlag=1;
            SystemClock.sleep(1000);
        }
    }

    private void wifiMonitor(final String reportName, final String wifiName, final String ip){
        isMonitor = true;
        Thread monitor =new Thread(new Runnable() {
            @Override
            public void run() {
                while(isMonitor) wifiMonitor0(reportName, wifiName, ip);
            }
        }) ;
        monitor.start();
    }

    private void UiMonitor(){
        Thread ui =new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        UiBase.clickIfObjExist(UiBase.objSelect[2],"(?i)GOT IT|.*知道了|No, thanks|不了，谢谢|我知道了|以后再说|暂不升级|Update later");
                        SystemClock.sleep(waitTime * 10);
                    } catch (UiObjectNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }) ;
        ui.start();
    }

    private void pingIP(String ip) {
        try {
            baiDuP = mDevice.executeShellCommand("ping -c 1 -w 100 www.baidu.com");
            routerP = mDevice.executeShellCommand("ping -c 1 -w 100 " + ip);
        } catch (IOException e) {
            baiDuP=routerP="";
        }
        if(baiDuP.contains("packets transmitted")) baiDuP="pass";
        else baiDuP="fail";
        if(routerP.contains("packets transmitted")) routerP="pass";
        else routerP="fail";
    }

    private interface cases{
        void run(String wifiName);
    }

    private void addTestCase(){
        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(tencent.equals("true")) playTencentVideo(tencent_play_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(douyin.equals("true")) playDouyin(refresh_gap,douyin_play_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(douyu.equals("true")) playDouyu(douyu_play_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(weibo.equals("true")) playWeibo(refresh_gap,weibo_play_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(internet.equals("true")) searchInternet(refresh_gap,internet_search_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(download.equals("true")) downloadApk(apk_address,wifiName);
            }
        });
    }

    private void changePrivacy(String name){
        if(Build.VERSION.SDK_INT == 29){
            try {
                UiBase.waitClickObj(UiBase.objSelect[0],name,3);
                UiBase.waitClickObj(UiBase.objSelect[2],"隐私|Privacy",3);
                UiBase.waitClickObj(UiBase.objSelect[2],"使用设备 MAC|Use device MAC",3);
                mDevice.pressBack();
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private void checkConnect(){
        NetworkInfo info = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        for(int i=0;i<60;i++){
            if(info.isConnected()) break;
            else Log.d(TAG,"not connect");
            SystemClock.sleep(waitTime);
            if(i==59) UiBase.checkPoint("connect wifi fail",false);
        }
    }

    @Test
    public void debug() throws Throwable {
        checkConnect();
    }


}
